package com.chaoyong.higo.activity;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chaoyong.higo.R;
import com.chaoyong.higo.adapter.SearchAdapter;
import com.chaoyong.higo.adapter.SearchAdapter.OnCartClick2;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.bean.GetAllGoodsBean_z;
import com.chaoyong.higo.bean.ListEntity;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.XListView;
import com.chaoyong.higo.view.XListView.IXListViewListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
/**
 * 2016.3.2
 * @author 丁晶
 *
 */
public class SearchActivity extends BaseActivity implements IXListViewListener, OnItemClickListener {
	
	private List<String> keys;
	private Map<String, String> map;
	private String[] mAllGoods;
	private LinearLayout search_keyword;
	private Activity context;
	private XListView xlv;
	private TextView tv_top_word;
	private List<ListEntity> data;
	private SearchAdapter adapter;
	private EditText search_word;
	private GetAllGoodsBean_z bean;
	
	@Override
	public int layoutResID() {
		return R.layout.activity_search;
	}
	private ImageButton back_imgbt;
	@Override
	public void findView() {
		back_imgbt=(ImageButton) findViewById(R.id.search_back_imgbt);
		search_keyword = (LinearLayout) findViewById(R.id.search_keyword);
		context = this;
		xlv = (XListView) findViewById(R.id.search_xlv);
		//xlv.setHintFooter();
		xlv.setPullLoadEnable(false);
		xlv.setPullRefreshEnable(false);
		xlv.setVerticalFadingEdgeEnabled(false);
		xlv.setXListViewListener(this);
		xlv.setOnItemClickListener(this);

		tv_top_word = (TextView) findViewById(R.id.search_hot_word);
		search_word = (EditText) findViewById(R.id.search_search_word);
		
		back_imgbt.setOnClickListener(this);
	}

	@Override
	public void init() {
		xlv.setVisibility(View.GONE);
		adapter = new SearchAdapter(context, null);
		xlv.setAdapter(adapter);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.search_back_imgbt:
			finish();
			break;

		default:
			break;
		}
	}
	
	/**
	 * 添加购物车
	 * 
	 * @param goodsIdAndExcept
	 *            拼接方式：id + "," + except
	 */
	private void httpAddToCars(String goodsIdAndExcept) {
		HttpUtils http = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object;
		try {
			object = new JSONObject();
			object.put("app", "1");
			object.put("model", "BuyRecord");
			object.put("function", "addCarList");
			object.put("code", goodsIdAndExcept);
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		http.send(HttpMethod.POST, Values.MAIN_RECOMMEND, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				try {
					JSONObject object = new JSONObject(arg0.result);
					String status = object.getString("status");
					String data = object.getString("data");
					if (status.equals("1")) {
						//showToast(data + "");
						showToast("已添加到购物车");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		search_keyword.removeAllViews();
		getClassification();
		
		adapter.setOnCartClickListener(new OnCartClick2(){

			@Override
			public void onCartClick(String id, String expect, Serializable sb) {
				// TODO Auto-generated method stub
				//showToast("已加入到购物车\n" + "商品id:" + id + "\n商品期数:" + expect);
				String goods = id + "," + 1;
				// TODO 添加到购物车，id：商品id，expect:这个字段其实添加的是购买的次数；在调用此接口时候，参数传入“8，9”
				httpAddToCars(goods);
				// 显示数字提醒
				/*if (badgeView.isShown()) {
					badgeView.increment(1);
				} else {
					badgeView.show();
				}*/
				
				// 显示数字提醒
				if (!Values.idList.contains(id)) {
					Values.idList.add(id);
					if (MainActivity.badgeView.isShown()) {
						MainActivity.badgeView.increment(1);
					} else {
						MainActivity.badgeView.show();
					}
				}
				
			}
			
		});
		
		/*adapter.setOnCartClickListener(new OnCartClick() {
			@Override
			public void onCartClick(String id, String expect, Serializable sb) {
				showToast("已加入到购物车\n" + "商品id:" + id + "\n商品期数:" + expect);
				String goods = id + "," + 1;
				// TODO 添加到购物车，id：商品id，expect:这个字段其实添加的是购买的次数；在调用此接口时候，参数传入“8，9”
				httpAddToCars(goods);
				// 显示数字提醒
				if (badgeView.isShown()) {
					badgeView.increment(1);
				} else {
					badgeView.show();
				}
			}
		});*/
	}
	
	@SuppressLint("NewApi")
	private void getClassification() {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("function", "setAndGet");
			json.put("name", "gps");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, OApi.Public_appRedis, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				showToast(arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				try {
					JSONObject jso = new JSONObject(result);
					JSONObject data = jso.getJSONObject("data");
					Iterator it = data.keys();
					keys = new ArrayList<String>();
					while (it.hasNext()) {
						String key = it.next().toString();
						keys.add(key);
					}
					Collections.sort(keys);
					//map = new HashMap<>();
					mAllGoods = new String[keys.size()];
					for (int i = 0; i < keys.size(); i++) {
						JSONObject js = data.getJSONObject(keys.get(i));
						mAllGoods[i] = js.getString("title");
						//map.put(js.getString("title"), js.getString("id"));
						TextView tv = new TextView(context);
						tv.setText(js.getString("title"));
						tv.setGravity(Gravity.CENTER);
						LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);  
						lp.setMargins(2, 10, 2, 10);  
						    tv.setLayoutParams(lp);   
						    tv.setPadding(5, 5, 5, 5);
						   // tv.setTextColor(Color.parseColor(""));
						    tv.setTextSize(14);
						//tv.setBackground(getResources().getDrawable(R.drawable.shape_search_text));
						    tv.setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									Intent intent = new Intent(context, MainActivity.class);
									intent.putExtra("tag", 1);
									startActivity(intent);
								}
							});
						search_keyword.addView(tv); 
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	
	public void onSearch(View view){
		String key_word = search_word.getText().toString();
		if(TextUtils.isEmpty(key_word)){
			//showToast("请输入关键词！");
			search_word.setError("请输入关键词");
			return ;
		}
		if(data != null){
			data.clear();
			adapter.changeDatas(null);
			adapter.notifyDataSetChanged();
		}
		xlv.removeAllViewsInLayout();
		xlv.setVisibility(View.VISIBLE);
		tv_top_word.setVisibility(View.GONE);
		search_keyword.setVisibility(View.GONE);
		httpQueryAllGoods(key_word);
	}
	
	private void httpQueryAllGoods(String key_word) {
		HttpUtils http = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object;
		try {
			object = new JSONObject();
			object.put("app", "1");
			object.put("model", "goods");
			object.put("function", "search");
			object.put("code", key_word);
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		http.send(HttpMethod.POST, Values.MAIN_RECOMMEND, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				showToast("失败" + arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				/*try {
					JSONObject jso = new JSONObject(result);
					Iterator it = jso.keys();
					keys = new ArrayList<String>();
					while (it.hasNext()) {
						String key = it.next().toString();
						keys.add(key);
					}
					showToast(keys.get(0) + keys.get(1) + keys.get(2));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
				try {
					JSONObject jso = new JSONObject(result);
					//JSONObject data = jso.getJSONObject("data");
					if(jso.getInt("status") == 1){
						/*if(data != null){
							data.clear();
							adapter.changeDatas(null);
							adapter.notifyDataSetChanged();
						}*/
						Gson gson = new Gson();
						bean = gson.fromJson(result, GetAllGoodsBean_z.class);
						if (bean.getStatus().equals("1")) {
							data = bean.getData().getList();
							
							if (!EmptyUtil.isEmpty(data)) {
								adapter.changeDatas(data);
							}
						}
					}else{
						showToast("没有搜索到相关商品");
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				/*try {
					JSONObject jso = new JSONObject(result);
					JSONObject dt = jso.getJSONObject("data");
					JSONArray ja = dt.getJSONArray("list");
					if(ja == null){
						showToast("没有数据");
					}else{
						data = new ArrayList<ListEntity>();
						for (int i = 0; i < ja.length(); i++) {
							JSONObject js = ja.getJSONObject(i);
							ListEntity en = new ListEntity();
							en.setId(js.getString("id"));
							en.setGoods_name(js.getString("goods_name"));	
							en.setGoods_expect(js.getString("goods_expect"));
							en.setCover_img(js.getString("cover_img"));
							en.setGoods_info(js.getString("goods_info"));
							en.setGoods_price(js.getString("goods_price"));
							en.setType_id(js.getString("type_id"));
							en.setParent_id(js.getString("parent_id"));
							en.setLimit_buy_num(js.getString("limit_buy_num"));
							en.setAuto_release(js.getString("auto_release"));
							en.setIs_down_line(js.getString("is_down_line"));
							en.setGoods_status(js.getString("goods_status"));
							en.setGoods_id(js.getString("goods_id"));
							en.setExpect(js.getString("expect"));
							en.setOpen_time(js.getString("open_time"));
							en.setSurplus(js.getInt("surplus"));
							data.add(en);
						}
						adapter.changeDatas(data);
					//}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					showToast("没有数据");
				}*/
			}
		});
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		showToast("已经刷新啦！");
		onLoad();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		showToast("没有更多数据啦！");
		onLoad();
	}

	private void onLoad() {
		xlv.stopRefresh();
		xlv.stopLoadMore();
		//xlv.setRefreshTime(times);
		//xlv.setRefreshTishi("上次刷新时间：");
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		//view.setBackgroundResource(R.color.gray_color);
		ListEntity entity = bean.getData().getList().get(position - 1);
		Intent i = new Intent(context, ProductDeTimeActivity.class);
		i.putExtra("listEntity", entity);
		startActivity(i);
	}
}
